package com.cs.zerocopy;

import java.io.FileInputStream;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;

/**
 * @ClassName: NewIOClient
 * @Description: TODO
 * @Author: kevin
 * @Date: 2020/8/10 11:20
 * @Version: 1.0
 */
public class NewIOClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress(7001));
        String fileName = "C:\\Users\\kevin\\IdeaProjects\\other\\network_programming\\my_netty\\NIO_demo\\protoc-3.6.1-win32.zip";

        // 得到一个文件channel
        FileChannel fileChannel = new FileInputStream(fileName).getChannel();

        // 准备发送
        long startTime = System.currentTimeMillis();

        // 在Linux下 一个 transferTo 方法就能完成传输
        // 在 Windows 下，一次调用 transferTo 只能发送8m，就需要分段传输文件，而且要注意传输时的位置
        // transferTo 底层使用到零拷贝
        long transferCount = fileChannel.transferTo(0, fileChannel.size(), socketChannel);

        System.out.println("发送的总的字节数 =" + transferCount + " 耗时:" + (System.currentTimeMillis() - startTime));

        // 关闭
        fileChannel.close();
    }
}
